﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using IGolovkine.Core.Diagnostics;
using IGolovkine.Core;

namespace IGolovkine.ShoutCastRipper
{
    public class StationConnection : IStationConnection
    {
        private const int SocketTimeout = 30000;
        private readonly Stream _stream;
        private readonly HttpWebResponse _response;
        private readonly int _dataLength;
        private string _currentContentTitle;

        private readonly ObjectDisposedCheck _isDisposedCheck;

        public StationConnection(string url, string userAgent)
        {
            Debug.NotNullOrEmpty(() => url);
            Debug.NotNullOrEmpty(() => userAgent);

            HttpWebRequest request = request = (HttpWebRequest) WebRequest.Create(url);
            request.Headers.Clear();
            request.Headers.Add("GET", "HTTP/1.0");
            request.Headers.Add("Icy-MetaData", "1");
            request.UserAgent = userAgent;

            _response = (HttpWebResponse) request.GetResponse();

            if (_response.StatusCode != HttpStatusCode.OK)
            {
                throw new IOException(string.Format("Invalid status code '{0}'", _response.StatusDescription));
            }

            _dataLength = GetIcyDataLength(_response);
            if (_dataLength == 0)
            {
                throw new IOException(string.Format("icy-metaint field is 0"));
            }

            _stream = _response.GetResponseStream();
            _isDisposedCheck = new ObjectDisposedCheck(this);
        }

        private static int GetIcyDataLength(HttpWebResponse response)
        {
            try
            {
                return Convert.ToInt32(response.GetResponseHeader("icy-metaint"));
            }
            catch (Exception ex)
            {
                throw new IOException("Error reading icy-metaint", ex);
            }
        }
        
        public string CurrentContentTitle
        {
            get { return _currentContentTitle; }
        }

        public byte[] ReadContentData()
        {
            _isDisposedCheck.EnsureNotDisposed();

            byte[] data = new byte[_dataLength];
            if (this.FillBuffer(data))
            {
                string newTitle = this.ReadContentTitle();
                if (this._currentContentTitle == null && newTitle == null)
                {
                    throw new IOException("Failed to read content title");
                }
                if (newTitle != null)
                {
                    _currentContentTitle = newTitle;
                }                
            }
            return data;
        }

        private string ReadContentTitle()
        {
            int metaDataLength = this.GetMetaDataLength();
            if (metaDataLength != 0)
            {
                byte[] headerData = new byte[metaDataLength];
                if (this.FillBuffer(headerData))
                {
                    string header = Encoding.Default.GetString(headerData);
                    return GetRecordingTitleFromHeader(header);
                }
            }
            return null;
        }
        
        private int GetMetaDataLength()
        {
            int b = _stream.ReadByte();
            if (b != -1)
            {
                return b * 16;
            }
            else
            {
                throw new IOException("Error reading Meta Data length from the stream");
            }
        }

        private bool FillBuffer(byte[] buffer)
        {
            int totalBytesRead = 0;
            while (totalBytesRead < buffer.Length && !_isDisposedCheck.IsDisposed)
            {
                IAsyncResult result = _stream.BeginRead(buffer, totalBytesRead, buffer.Length - totalBytesRead, null, null);
                if (result.AsyncWaitHandle.WaitOne(SocketTimeout))
                {
                    int bytesRead = _stream.EndRead(result);
                    totalBytesRead += bytesRead;
                }
                else
                {
                    throw new IOException("Stream reading operation has timed out");
                }
            }
            return !_isDisposedCheck.IsDisposed;
        }

        public bool IsClosed
        {
            get { return this._isDisposedCheck.IsDisposed; }
        }
        
        public void Close()
        {
            this.Dispose();
        }

        public void Dispose()
        {
            _isDisposedCheck.Dispose();
            _stream.Dispose();
        }

        private static string GetRecordingTitleFromHeader(string metadataHeader)
        {
            string recordingName = Regex.Match(metadataHeader, "(StreamTitle=')(.*)(';StreamUrl)").Groups[2].Value.Trim();
            recordingName = recordingName.Replace(":", "");
            recordingName = recordingName.Replace("/", "");
            recordingName = recordingName.Replace("\\", "");
            recordingName = recordingName.Replace("<", "");
            recordingName = recordingName.Replace(">", "");
            recordingName = recordingName.Replace("|", "");
            recordingName = recordingName.Replace("?", "");
            recordingName = recordingName.Replace("*", "");
            recordingName = recordingName.Replace("\"", "");
            recordingName = RemoveLeadingNumber(recordingName);
            return recordingName;
        }

        private static string RemoveLeadingNumber(string value)
        {
            StringBuilder buffer = new StringBuilder(value.Length);
            foreach (char c in value)
            {
                if (Char.IsNumber(c) == false || buffer.Length != 0)
                {
                    buffer.Append(c);
                }
            }
            return buffer.ToString().TrimStart();
        }
    }
}
